# -*- coding: utf-8 -*-

from autoadmin.lib.base import *
from autoadmin.lib.util import LoggerHandler
from autoadmin.lib.finder import *
from autoadmin.lib.manipulator import ManipulatorSchema, NewManipulator
from autoadmin.lib.schema.default import *
from autoadmin.lib.field import handler

from autoadmin.model import Session, forms

import sqlalchemy.schema

class EditController(BaseController):
    
    log = LoggerHandler()
    
    def _get_model_object(self, model_class, model_object_id):
        return Session.query(model_class).\
                    filter_by(id=model_object_id).one()
    
    def _get_model_class(self, model_name):
        try:
            return g.model_finder.get_model(model_name)
        except ModelFinderError, error:
            self.log.exception(error)
            return ''
        
    def edit_form(self, model_name, model_object_id):
        
        model_class = self._get_model_class(model_name)
        model_object = self._get_model_object(model_class, model_object_id)
        
        # Описывает, что должен делать манипулятор с колонками разного типа
        # например тут, для простой колонки вызвывается обработчик column
        fields_manipulate_schema = ManipulatorSchema({
            sqlalchemy.schema.Column : handler.column})
        fields_manipulate_schema.default_schema = handler.model
        
        models_manipulate_schema = ManipulatorSchema()
        models_manipulate_schema.default_schema = SimpleModelManipulateSchema
        
        field_manipulator = NewManipulator(model_object, fields_manipulate_schema,
            models_manipulate_schema)
        
        c.model_name = model_name
        c.model_object_id = model_object_id
        c.form_fields = field_manipulator.manipulate()

        return render('/edit.mako')
    
    @validate(forms.VariableForm(),form='edit_form')
    def save(self):
        
        model_name = self.form_result.pop('_model_name')
        model_object_id = self.form_result.pop('_model_object_id')
        
        model_class = self._get_model_class(model_name)        
        model_object = self._get_model_object(model_class, model_object_id)

        for field_name in self.form_result.keys():   
            if hasattr(model_object, field_name) and not field_name=='id':
                # хак, нужно как-то нормалньо сделать
                if not self.form_result[field_name]:
                    self.form_result[field_name] = None
                    
                setattr(model_object, field_name, self.form_result[field_name])
        
        Session.update(model_object)
        Session.flush()
        
        return redirect_to('edit object', model_name = model_name, 
                    model_object_id =model_object_id)
